package org.example.Thread01;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class MyThreadPool {
    BlockingQueue<Runnable> queue=new LinkedBlockingQueue<>(100);
    public MyThreadPool(int threadNum){
        if(threadNum<=0){
            throw new IllegalArgumentException("线程数量必须大于0");
        }
        //创建线程
        for(int i=0;i<threadNum;i++){
            Thread thread = new Thread(()->{
                //不停地扫描
                while(true){
                    try {
                        //从队列中取出任务
                        Runnable runnable=queue.take();
                        //执行任务
                        runnable.run();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            //启动线程
            thread.start();
        }
    }

    /**
     * 提交任务到线程池
     * @param runnable 具体提交的任务
     * @throws InterruptedException
     */
    public void submit(Runnable runnable) throws InterruptedException {
        if(runnable==null){
            throw new IllegalArgumentException("任务不能为空.");
        }
        queue.put(runnable);
    }
}
